package chapters19;

import java.util.concurrent.CountDownLatch;

/**
 * Created by xinxuchu on 2020/2/7.
 *
 * 使用CountDownLatch实现主从协作场景
 *
 * 在主从协作模式中，主线程依赖工作线程的结果，需要等待工作线程结束，
 * 这时，计数初始值为工作线程的个数，工作线程结束后调用count-Down，主线程调用await进行等待，
 */
public class MasterWorkerDemo {

    static class Worker extends Thread{
        CountDownLatch latch;

        public Worker(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run(){
            try {
                //模拟执行任务
                Thread.sleep((int)(Math.random()*1000));
                //模拟异常情况
                if (Math.random()<0.02){
                    throw new RuntimeException("bad luck!");
                }
            }catch (InterruptedException e){
            }finally {
                this.latch.countDown();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int workNum = 100;
        CountDownLatch latch = new CountDownLatch(workNum);
        Worker[] workers = new Worker[workNum];
        for (int i = 0; i < workNum; i++) {
            workers[i] = new Worker(latch);
            workers[i].start();
        }
        latch.await();
        System.out.println("collections worker result!");
    }
}
